import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Inject,
  Res,
  Headers,
  UnauthorizedException,
} from '@nestjs/common';
import { TagService } from './tag.service';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { JwtService } from '@nestjs/jwt';
import { Response } from 'express';

@Controller('tag')
export class TagController {
  constructor(private readonly tagService: TagService) {}

  @Inject(JwtService)
  private readonly jwtService: JwtService;

  @Post()
  create(@Body() createTagDto: CreateTagDto) {
    return this.tagService.create(createTagDto);
  }

  @Get()
  findAll(
    @Headers('authorization') authorization: string,
    @Res({ passthrough: true }) response: Response,
  ) {
    // return this.tagService.findAll();
    if (authorization) {
      try {
        const token = authorization.split(' ')[1];
        const data = this.jwtService.verify(token);
        console.log('=====token=====');
        console.log(data);
        const newToken = this.jwtService.sign({ id: data.id + 1 });
        response.header('token', newToken);
        return data.id + 1;
      } catch (error) {
        console.log('=====authorization=====');
        console.log(authorization);
        console.log(error);
        throw new UnauthorizedException();
      }
    } else {
      const token = this.jwtService.sign({ id: 1 });
      response.header('token', token);
      return 1;
    }
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.tagService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateTagDto: UpdateTagDto) {
    return this.tagService.update(+id, updateTagDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.tagService.remove(+id);
  }
}
